<template>
  <div class="production-efficiency">
    <div class="page-container">
      <!-- 页面标题和日期筛选 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">生产效率统计</h1>
          <div class="date-filter">
            <a-range-picker
              v-model="dateRange"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
              @change="onDateRangeChange"
              :allowClear="true"
              style="width: 240px; margin-right: 12px"
            />
            <a-button type="primary" @click="refreshData" :loading="loading">
              <a-icon type="reload" />
              刷新数据
            </a-button>
          </div>
        </div>
      </div>

      <!-- 基础数据卡片 -->
      <div class="data-cards-grid">
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              生产计划完成率统计已完成的生产计划数量占总计划数量的百分比。反映生产计划执行情况。
            </template>
            <div class="card-title">
              生产计划完成率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatPercentage(overviewData.planCompletionRate) }}</span>
            <span class="value-unit">%</span>
          </div>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title">
              任务按时完成率统计按时完成的任务数量占已完成任务总数的百分比。反映生产效率和时间管理水平。
            </template>
            <div class="card-title">
              任务按时完成率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatPercentage(overviewData.onTimeCompletionRate) }}</span>
            <span class="value-unit">%</span>
          </div>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 平均生产周期统计从任务开始到完成的平均天数。反映生产效率和流程优化程度。 </template>
            <div class="card-title">
              平均生产周期
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number">{{ formatNumber(overviewData.averageProductionCycle) }}</span>
            <span class="value-unit">天</span>
          </div>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 员工生产效率统计员工预计工时与实际工时的比率。大于100%表示效率高于预期。 </template>
            <div class="card-title">
              员工生产效率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
          </a-tooltip>
          <div class="card-value">
            <span class="value-number" :class="getEfficiencyClass(overviewData.employeeEfficiency)">
              {{ formatPercentage(overviewData.employeeEfficiency) }}
            </span>
            <span class="value-unit">%</span>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <!-- 第一行图表 -->
        <div class="charts-row">
          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">生产计划vs实际完成对比</h3>
              <div class="chart-controls">
                <a-radio-group v-model="planVsActualTimeType" @change="updatePlanVsActualChart">
                  <a-radio-button value="month">月度</a-radio-button>
                  <a-radio-button value="quarter">季度</a-radio-button>
                  <a-radio-button value="year">年度</a-radio-button>
                </a-radio-group>
              </div>
            </div>
            <div class="chart-content">
              <div ref="planVsActualChart" class="chart"></div>
            </div>
          </div>

          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">生产效率趋势</h3>
              <div class="chart-controls">
                <a-radio-group v-model="trendTimeType" @change="updateTrendChart">
                  <a-radio-button value="month">月度</a-radio-button>
                  <a-radio-button value="quarter">季度</a-radio-button>
                  <a-radio-button value="year">年度</a-radio-button>
                </a-radio-group>
              </div>
            </div>
            <div class="chart-content">
              <div ref="trendChart" class="chart"></div>
            </div>
          </div>
        </div>

        <!-- 第二行图表 -->
        <div class="charts-row">
          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">工序耗时分析</h3>
            </div>
            <div class="chart-content">
              <div ref="processTimeChart" class="chart"></div>
            </div>
          </div>

          <div class="chart-card">
            <div class="chart-header">
              <h3 class="chart-title">任务状态分布</h3>
            </div>
            <div class="chart-content">
              <div ref="taskStatusChart" class="chart"></div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getAction } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'ProductionEfficiency',
  data() {
    return {
      loading: false,
      dateRange: [],
      planVsActualTimeType: 'month',
      trendTimeType: 'month',

      // 概览数据
      overviewData: {
        planCompletionRate: 0,
        onTimeCompletionRate: 0,
        averageProductionCycle: 0,
        employeeEfficiency: 0,
      },

      // 图表实例
      charts: {
        planVsActual: null,
        trend: null,
        processTime: null,
        taskStatus: null,
      },
    }
  },

  mounted() {
    this.initDateRange()
    this.initCharts()
    this.loadData()
  },

  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach((chart) => {
      if (chart) {
        chart.dispose()
      }
    })

    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize)
  },

  methods: {
    initDateRange() {
      // 默认显示最近30天的数据
      const endDate = moment()
      const startDate = moment().subtract(30, 'days')
      this.dateRange = [startDate, endDate]
    },

    initCharts() {
      this.$nextTick(() => {
        this.charts.planVsActual = echarts.init(this.$refs.planVsActualChart)
        this.charts.trend = echarts.init(this.$refs.trendChart)
        this.charts.processTime = echarts.init(this.$refs.processTimeChart)
        this.charts.taskStatus = echarts.init(this.$refs.taskStatusChart)

        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResize)
      })
    },

    handleResize() {
      Object.values(this.charts).forEach((chart) => {
        if (chart) {
          chart.resize()
        }
      })
    },

    async loadData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadOverviewData(),
          this.loadPlanVsActualData(),
          this.loadTrendData(),
          this.loadProcessTimeData(),
          this.loadTaskStatusData(),
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    async loadOverviewData() {
      const params = this.getDateParams()
      const res = await getAction('/mes/statistics/production/efficiency/overview', params)
      if (res.success) {
        this.overviewData = res.result || {}
      }
    },

    async loadPlanVsActualData() {
      const params = {
        ...this.getDateParams(),
        timeType: this.planVsActualTimeType,
      }
      const res = await getAction('/mes/statistics/production/efficiency/plan-vs-actual', params)
      if (res.success && res.result) {
        this.updatePlanVsActualChartData(res.result)
      }
    },

    async loadTrendData() {
      const params = {
        ...this.getDateParams(),
        timeType: this.trendTimeType,
      }
      const res = await getAction('/mes/statistics/production/efficiency/trend', params)
      if (res.success && res.result) {
        this.updateTrendChartData(res.result)
      }
    },

    async loadProcessTimeData() {
      const params = this.getDateParams()
      const res = await getAction('/mes/statistics/production/efficiency/process-time', params)
      if (res.success && res.result) {
        this.updateProcessTimeChartData(res.result)
      }
    },

    async loadTaskStatusData() {
      const params = this.getDateParams()
      const res = await getAction('/mes/statistics/production/efficiency/task-status', params)
      if (res.success && res.result) {
        this.updateTaskStatusChartData(res.result)
      }
    },

    getDateParams() {
      if (this.dateRange && this.dateRange.length === 2) {
        return {
          startDate: this.dateRange[0].format('YYYY-MM-DD'),
          endDate: this.dateRange[1].format('YYYY-MM-DD'),
        }
      }
      return {}
    },

    updatePlanVsActualChartData(data) {
      const planData = data.planData || []
      const actualData = data.actualData || []

      const categories = [
        ...new Set([...planData.map((item) => item.time_period), ...actualData.map((item) => item.time_period)]),
      ].sort()

      const planValues = categories.map((period) => {
        const item = planData.find((d) => d.time_period === period)
        return item ? item.plan_quantity || 0 : 0
      })

      const actualValues = categories.map((period) => {
        const item = actualData.find((d) => d.time_period === period)
        return item ? item.actual_quantity || 0 : 0
      })

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['计划数量', '实际完成'],
        },
        xAxis: {
          type: 'category',
          data: categories,
        },
        yAxis: {
          type: 'value',
          name: '数量',
        },
        series: [
          {
            name: '计划数量',
            type: 'bar',
            data: planValues,
            itemStyle: {
              color: '#1890ff',
            },
          },
          {
            name: '实际完成',
            type: 'bar',
            data: actualValues,
            itemStyle: {
              color: '#52c41a',
            },
          },
        ],
      }

      this.charts.planVsActual.setOption(option)
    },

    updateTrendChartData(data) {
      const categories = data.map((item) => item.time_period)
      const efficiencyData = data.map((item) => item.efficiency_rate || 0)
      const onTimeData = data.map((item) => item.on_time_rate || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['工时效率率', '按时完成率'],
        },
        xAxis: {
          type: 'category',
          data: categories,
        },
        yAxis: {
          type: 'value',
          name: '百分比 (%)',
          min: 0,
          max: 150,
        },
        series: [
          {
            name: '工时效率率',
            type: 'line',
            data: efficiencyData,
            smooth: true,
            itemStyle: {
              color: '#1890ff',
            },
          },
          {
            name: '按时完成率',
            type: 'line',
            data: onTimeData,
            smooth: true,
            itemStyle: {
              color: '#52c41a',
            },
          },
        ],
      }

      this.charts.trend.setOption(option)
    },

    updateProcessTimeChartData(data) {
      const categories = data.map((item) => item.work_type_name)
      const avgDays = data.map((item) => item.avg_days || 0)
      const avgHours = data.map((item) => item.avg_hours || 0)
      const efficiencyRates = data.map((item) => item.efficiency_rate || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              if (param.seriesName === '效率率') {
                result += param.marker + param.seriesName + ': ' + param.value + '%<br/>'
              } else {
                result += param.marker + param.seriesName + ': ' + param.value + (param.seriesName.includes('天数') ? '天' : '小时') + '<br/>'
              }
            })
            return result
          }
        },
        legend: {
          data: ['平均天数', '平均工时', '效率率'],
        },
        xAxis: {
          type: 'category',
          data: categories,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '天数/工时',
            position: 'left',
          },
          {
            type: 'value',
            name: '效率率 (%)',
            position: 'right',
            max: 120,
          }
        ],
        series: [
          {
            name: '平均天数',
            type: 'bar',
            yAxisIndex: 0,
            data: avgDays,
            itemStyle: {
              color: '#ff7875',
            },
          },
          {
            name: '平均工时',
            type: 'bar',
            yAxisIndex: 0,
            data: avgHours,
            itemStyle: {
              color: '#40a9ff',
            },
          },
          {
            name: '效率率',
            type: 'line',
            yAxisIndex: 1,
            data: efficiencyRates,
            itemStyle: {
              color: '#52c41a',
            },
            lineStyle: {
              width: 2,
            },
            symbol: 'circle',
            symbolSize: 6,
          },
        ],
      }

      this.charts.processTime.setOption(option)
    },

    updateTaskStatusChartData(data) {
      const pieData = data.map((item) => ({
        name: item.status_name,
        value: item.task_count || 0,
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '任务状态',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }

      this.charts.taskStatus.setOption(option)
    },

    onDateRangeChange() {
      this.loadData()
    },

    refreshData() {
      this.loadData()
    },

    updatePlanVsActualChart() {
      this.loadPlanVsActualData()
    },

    updateTrendChart() {
      this.loadTrendData()
    },

    formatNumber(value) {
      if (value === null || value === undefined) return '0'
      return Number(value).toFixed(1)
    },

    formatPercentage(value) {
      if (value === null || value === undefined) return '0.00'
      return Number(value).toFixed(2)
    },

    getEfficiencyClass(value) {
      const numValue = Number(value)
      if (numValue >= 100) {
        return 'efficiency-high'
      } else if (numValue >= 80) {
        return 'efficiency-medium'
      } else {
        return 'efficiency-low'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.production-efficiency {
  background-color: #f0f2f5;
  min-height: 100vh;

  .page-container {
    padding: 24px;
    max-width: 1400px;
    margin: 0 auto;
  }

  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    padding: 24px 32px;
    margin-bottom: 24px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        font-size: 28px;
        font-weight: 600;
        color: #ffffff;
        margin: 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .date-filter {
        display: flex;
        align-items: center;
        gap: 12px;

        .ant-btn-primary {
          background: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          font-weight: 500;
          backdrop-filter: blur(10px);
          transition: all 0.3s ease;

          &:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-1px);
          }
        }

        .ant-calendar-picker {
          .ant-calendar-picker-input {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            backdrop-filter: blur(10px);

            &:hover {
              border-color: rgba(255, 255, 255, 0.5);
            }
          }
        }
      }
    }
  }

  .data-cards-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 24px;
    margin-bottom: 24px;

    .data-card {
      background: white;
      border-radius: 8px;
      padding: 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      transition: transform 0.2s ease, box-shadow 0.2s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
      }

      .card-title {
        font-size: 14px;
        color: #8c8c8c;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
      }

      .card-value {
        display: flex;
        align-items: baseline;

        .value-number {
          font-size: 32px;
          font-weight: 600;
          color: #262626;
          margin-right: 4px;

          &.efficiency-high {
            color: #52c41a;
          }

          &.efficiency-medium {
            color: #faad14;
          }

          &.efficiency-low {
            color: #ff4d4f;
          }
        }

        .value-unit {
          font-size: 16px;
          color: #8c8c8c;
        }
      }
    }
  }

  .charts-container {
    .charts-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }

      .chart-card {
        background: white;
        border-radius: 8px;
        padding: 24px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

        &.full-width {
          grid-column: 1 / -1;
        }

        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;

          .chart-title {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #262626;
          }

          .chart-controls {
            display: flex;
            align-items: center;
            gap: 12px;
          }
        }

        .chart-content {
          .chart {
            width: 100%;
            height: 400px;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .production-efficiency {
    .page-container {
      padding: 16px;
    }

    .charts-container {
      .charts-row {
        grid-template-columns: 1fr;

        .chart-card {
          &.full-width {
            grid-column: 1;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .production-efficiency {
    .page-header {
      .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;

        .page-title {
          font-size: 20px;
        }

        .date-filter {
          justify-content: center;
        }
      }
    }

    .data-cards-grid {
      grid-template-columns: 1fr;
    }

    .charts-container {
      .charts-row {
        .chart-card {
          .chart-content {
            .chart {
              height: 300px;
            }
          }
        }
      }
    }
  }
}
</style>
